// store/index.js  
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    showConsole: true, // 控制台是否显示
    showDetails: true, // 详情是否显示

    msg_error: null, // 错误信息
    log_data: [], // 日志数据

    status_deviceSelect: null, // 设备选择状态
    DeviceStatus: null, // 设备状态
    socket: null,
    status_ws: 'disconnected', // 存储WebSocket连接状态
    websocketData: 'hlly777', // 存储从 WebSocket 接收到的数据  
    TcpServerData: 'hlly777' // 存储从 TcpServer 接收到的数据
  },
  mutations: {
    setSocket(state, socket) {
      state.socket = socket;
    },
    updateWebsocketData(state, data) {
      state.websocketData = data;
    },
    updateTcpServerData(state, data) {
      state.TcpServerData = data;
    }
  },
  actions: {
    openSocket({ commit }) {
      console.log(this.state.status_ws);
      if (this.state.status_ws === 'connected') return
      const socket = new WebSocket('ws://10.0.0.170:8020/ws/chat');

      socket.onopen = () => {
        console.log('WebSocket Connected');
        commit('setSocket', socket);
        this.state.status_ws = 'connected'; // 更新WebSocket连接状态
      };

      socket.onerror = (error) => {
        console.error('WebSocket Error: ', error);
      };

      socket.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          const msgType = data.msgType
          const msg = data.message
          // const msg = JSON.stringify(message);
          if (msgType === 'msgType_WebSocketDebug') {
            this.state.websocketData = msg
          } else if (msgType === 'msgType_TcpDebug') {
            this.state.TcpServerData = msg
          } else if (msgType === 'msgType_Log') {
            this.state.log_data = msg
          } else if (msgType === 'msgType_DeviceStatus') {
            this.state.DeviceStatus = msg
          }
        } catch (error) {
          console.error("解析JSON失败:", error);  
          console.log(event.data)
        }
        };

      socket.onclose = () => {
        console.log('WebSocket Connection Closed')
        this.state.status_ws = 'disconnected'; // 更新WebSocket连接状态
      };
    },
    sendMessage({ commit, state }, message) {
      if (state.socket && state.socket.readyState === WebSocket.OPEN) {
        if (this.state.status_deviceSelect) {
          state.socket.send(JSON.stringify(message));
          console.log('Message sent to server: ', message);
        } else {
          const msg = "请先选择设备！";
          state.msg_error = msg
          console.log(msg)
        }
      }
    }
  }
});